home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part2 / 10078 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  56.5 KB

  1. Path: sun.soe.clarkson.edu!cline
  2. From: cline@sun.soe.clarkson.edu (Marshall Cline)
  3. Newsgroups: comp.lang.c++
  4. Subject: C++ FAQ: posting #1/4
  5. Followup-To: comp.lang.c++
  6. Date: 6 Mar 1996 02:20:52 GMT
  7. Organization: Paradigm Shift, Inc (technology consulting)
  8. Sender: cline@sun.soe.clarkson.edu
  9. Distribution: world
  10. Expires: +1 month
  11. Message-ID: <4hisq4$hfj@library.erc.clarkson.edu>
  12. Reply-To: cline@parashift.com (Marshall Cline)
  13. NNTP-Posting-Host: sun.soe.clarkson.edu
  14. Summary: Please read this before posting to comp.lang.c++
  15. Archive-name: C++-faq/part1_4
  16.  
  17. comp.lang.c++ Frequently Asked Questions list (with answers, fortunately).
  18. Copyright (C) 1991-96 Marshall P. Cline, Ph.D.
  19. Posting 1 of 4.
  20.  
  21. UPDATED 3/96:
  22.  * Added a FAQ on whether C++ is better than Ada (or Visual Basic or ...)
  23.  * Added WWW and anonymous ftp addresses:
  24.     http://www.connobj.com/cpp/cppfaq.htm
  25.     ftp://rtfm.mit.edu/pub/usenet-by-group/comp.lang.c++/
  26.  * Added a new FAQ on heterogeneous containers
  27.  * Modified the FAQs covering coding standards
  28.  * Added an Acronyms section for things like ARM, C++PL2, etc.
  29.  * Updated the dynamic-typing FAQs to reflect dynamic_cast and typeid()
  30.  * Updated the ftp address for C++2LaTeX
  31.  * Added a new LaTeX macro for pretty-printing the name "C++"
  32.  * Added a paragraph in the FAQ on mixing new and free, or malloc and delete
  33.  * Corrected an error in the on-line location for the ANSI-C++ draft standard
  34.  * Corrected a access-level error in FAQ 45.
  35.  * Added a note to FAQ 129
  36.  * Fixed the "iostream vs stdio" FAQ
  37.  * Fixed a typo in FAQ 111
  38.  * Corrected numerous typographical errors
  39.  
  40. UPDATED 1/96:
  41.  * Anonymous ftp fron.soe.clarkson.edu still does not work.
  42.  * No significant changes were made this month.
  43.  
  44. UPDATED 9/95:
  45.  * Added FAQ 41 on using a variable for the first dimension of a
  46.    multi-dimensional array
  47.  * Added FAQ 123 on the code from "Numerical Recipes"
  48.  * Added section 20 ("Libraries").  It's still pretty sparse, but it's a start
  49.  * Fixed a bug in FAQ 30 (there was no variable "i")
  50.  * Added FAQ 124 on dynamic linking to avoid bloated executables
  51.  * Added FAQ 32 on trying to "reopen" cin and cout in binary mode
  52.  * Added the access info to get the ANSI/ISO Committee Draft via ftp (FAQ 7)
  53.  
  54. UPDATED 7/95:
  55.  * Minor stuff (but not change in FTP access, below).
  56.  
  57. UPDATED 6/95:
  58.  * Corrected the mailing address where the ANSI-C++ Draft can be ordered
  59.  * Added a FAQ on floating point [Thanks to Phil Staite]
  60.  * Added a FAQ on multidimensional arrays [Thanks to Doug Shapter]
  61.  * Added a FAQ on interrupt service routines and ptrs to member functions
  62.  * Reorganized the FAQ on allocating all objects of a certain class via 'new'
  63.  
  64. UPDATED 5/95:
  65.  * Minor cosmetic changes
  66.  
  67. UPDATED 4/95:
  68.  * Added a question on a common BC++ Windows issue
  69.  * Fixed the ftp address for NIHCL
  70.  * Added an explanation that "ARM" is short for "Annotated Reference Manual"
  71.  
  72. UPDATED 3/95:
  73.  * Added a question on "delete this"
  74.  * Added two questions on iostreams and eof
  75.  * Fixed the entry on "c-mode" and "cc-mode" in Gnu emacs
  76.  
  77. UPDATED 1/95:
  78.  * A Chinese version of this document has been produced; details below.
  79.  
  80. UPDATED 12/94:
  81.  * Added a FAQ on STL (currently #115).
  82.  * Added a FAQ on name mangling (currently #119).
  83.  * Fixed typo in FAQ that compared composition with private inheritance.
  84.  * Corrected some spelling errors.
  85.  
  86. UPDATED 11/94:
  87.  * Added differentiator between "FAQ book" and "FAQ posting"
  88.  * Other cosmetic changes
  89.  
  90. UPDATED 10/94:
  91.  * Fixed a few typos
  92.  
  93. UPDATED 9/94:
  94.  * Minor cosmetic changes
  95.  
  96. UPDATED 8/94:
  97.  * Made it up-to-date with respect to "typeid" and "dynamic_cast".
  98.  * Made it up-to-date with respect to "mutable" and "const_cast".
  99.  * Rewrote most of the answers to provide general cleanup.
  100.  * The quotation marks are now "..." rather than `...' or ``...''
  101.  * Sample code lines start with a tab; no other lines starts with a tab.
  102.  * Everything was edited; minor modifications everywhere.
  103.  
  104. ==============================================================================
  105. SECTION 1: Introduction and table of contents
  106. ==============================================================================
  107.  
  108.     DOCUMENT:    Frequently-Asked-Questions for comp.lang.c++
  109.     REVISION:    Mar 5, 1996
  110.  
  111.     POSTING!=BOOK:    This C++ FAQ posting is NOT the same as the "FAQ book".
  112.             The "FAQ book" ("C++ FAQs", Addison-Wesley, 1995) is
  113.             5x larger than this posting.  See below for more.
  114.  
  115.     AUTHOR:        Marshall P. Cline, Ph.D.
  116.             Paradigm Shift, Inc.
  117.             One Park St. / Norwood, NY  13668
  118.             voice: 315-353-6100
  119.             fax:   315-353-6110
  120.             email: cline@parashift.com
  121.  
  122.     COPYRIGHT:    Copyright (C), 1991-96 Marshall P. Cline, Ph.D.
  123.             Permission to copy all or part of this work is granted,
  124.             provided that the copies are not made or distributed
  125.             for resale (except a nominal copy fee may be charged),
  126.             and provided that the AUTHOR, COPYRIGHT, & NO WARRANTY
  127.             sections are retained verbatim and are displayed
  128.             conspicuously.  If anyone needs other permissions that
  129.             aren't covered by the above, please contact the author.
  130.  
  131.     NO WARRANTY:    THIS WORK IS PROVIDED ON AN "AS IS" BASIS.  THE AUTHOR
  132.             PROVIDES NO WARRANTY WHATSOEVER, EITHER EXPRESS OR
  133.             IMPLIED, REGARDING THE WORK, INCLUDING WARRANTIES WITH
  134.             RESPECT TO ITS MERCHANTABILITY OR FITNESS FOR ANY
  135.             PARTICULAR PURPOSE.
  136.  
  137.     AVAILABILITY:    http://www.connobj.com/cpp/cppfaq.htm
  138.             ftp://rtfm.mit.edu/pub/usenet-by-group/comp.lang.c++/
  139.  
  140.     SEE ALSO:    comp.lang.c FAQ appears every month in that newsgroup,
  141.             and is maintained by Steve Summit (scs@eskimo.com).
  142.  
  143.     CHINESE TRANSLATION: A Chinese translation, encoded in "Big5" code
  144.             (a 16-bit Chinese code used mostly in Taiwan)
  145.             is now available for anonymous ftp at:
  146.          ftp://ftp.cis.nctu.edu.tw/Documents/News/comp.lang.c++/c-cppfaq.*
  147.  
  148. ==============================================================================
  149. SUBSECTION 1A: "FAQ book" versus "FAQ posting"
  150. ==============================================================================
  151.  
  152. Q1: Where can I download the C++ FAQ?
  153.  
  154.     http://www.connobj.com/cpp/cppfaq.htm
  155. or
  156.     ftp://rtfm.mit.edu/pub/usenet-by-group/comp.lang.c++/
  157.  
  158. ==============================================================================
  159.  
  160. Q2: Is there a C++FAQ book I can buy in a bookstore?
  161.  
  162. Yes.  "C++ FAQs" by Cline and Lomow, Addison-Wesley, 1995, ISBN 0-201-58958-3.
  163.  
  164. ==============================================================================
  165.  
  166. Q3: Why would I spend good money on a book when I can download it for free?
  167.  
  168. Because the book contains five times more material than this on-line document.
  169.  
  170. Many people have asked about the relationship between the book ("C++ FAQs",
  171. ISBN 0-201-58958-3) and this on-line document.  Some have wondered whether the
  172. posting is equivalent to the book.
  173.  
  174. The "FAQ book" is loosely based on the same concepts as this on-line document.
  175. However the FAQ book is approximately five (5) times bigger than this on-line
  176. document.  For example, the book's discussisons are much more detailed than in
  177. the on-line document, and the variety of FAQs is much wider in the book.  The
  178. book also includes thousands of cross references, external references, and
  179. index terms, as well as many programming examples.
  180.  
  181. ==============================================================================
  182. SUBSECTION 1B: Table of Contents
  183. ==============================================================================
  184.  
  185. ========== POSTING #1 ==========
  186.  
  187. SECTION 1: Introduction and table of contents
  188. SUBSECTION 1A: "FAQ book" versus "FAQ posting"
  189. Q1: Where can I download the C++ FAQ?
  190. Q2: Is there a C++FAQ book I can buy in a bookstore?
  191. Q3: Why would I spend good money on a book when I can download it for free?
  192. SUBSECTION 1B: Table of Contents
  193. SUBSECTION 1C: Nomenclature, Acronyms, and Common Abbreviations
  194.  
  195. SECTION 2: How should I post something? (READ BEFORE POSTING)
  196. Q4: Which newsgroup should I post my questions?
  197. Q5: How do I post a question about code that doesn't work correctly?
  198.  
  199. SECTION 3: Environmental/managerial issues
  200. Q6: What is OOP?  What is C++?
  201. Q7: Is C++ better than Ada? (or Pascal, C, FORTRAN, Visual Basic, or any other
  202.    language?)
  203. Q8: What are some advantages of C++?
  204. Q9: Who uses C++?
  205. Q10: Are there any C++ standardization efforts underway?
  206. Q11: Where can I get a copy of the latest ANSI-C++ draft standard?
  207. Q12: Is C++ backward compatible with ANSI-C?
  208. Q13: How long does it take to learn C++?
  209.  
  210. SECTION 4: Basics of the paradigm
  211. Q14: What is a class?
  212. Q15: What is an object?
  213. Q16: What is a reference?
  214. Q17: What happens if you assign to a reference?
  215. Q18: How can you reseat a reference to make it refer to a different object?
  216. Q19: When should I use references, and when should I use pointers?
  217. Q20: What's the deal with inline functions?
  218.  
  219. SECTION 5: Constructors and destructors
  220. Q21: What's the deal with constructors?
  221. Q22: How can I make a constructor call another constructor as a primitive?
  222. Q23: What's the deal with destructors?
  223.  
  224. SECTION 6: Operator overloading
  225. Q24: What's the deal with operator overloading?
  226. Q25: What operators can/cannot be overloaded?
  227. Q26: Can I create a "**" operator for "to-the-power-of" operations?
  228.  
  229. SECTION 7: Friends
  230. Q27: What is a "friend"?
  231. Q28: Do "friends" violate encapsulation?
  232. Q29: What are some advantages/disadvantages of using friend functions?
  233. Q30: What does it mean that "friendship is neither inherited nor transitive"?
  234. Q31: Should my class declare a member function or a friend function?
  235.  
  236. SECTION 8: Input/output via <iostream.h> and <stdio.h>
  237. Q32: How can I provide printing for a "class Fred"?
  238. Q33: Why should I use <iostream.h> instead of the traditional <stdio.h>?
  239. Q34: Why does my input seem to process past the end of file?
  240. Q35: Why is my program ignoring my input request after the first iteration?
  241. Q36: How can I "reopen" cin and cout in binary mode under DOS and/or OS/2?
  242.  
  243. ========== POSTING #2 ==========
  244.  
  245. SECTION 9: Freestore management
  246. Q37: Does "delete p" delete the pointer "p", or the pointed-to-data, "*p"?
  247. Q38: Can I "free()" pointers allocated with "new"?  Can I "delete" pointers
  248.    alloc'd with "malloc()"?
  249. Q39: Why should I use "new" instead of trustworthy old malloc()?
  250. Q40: Why doesn't C++ have a "realloc()" along with "new" and "delete"?
  251. Q41: How do I allocate / unallocate an array of things?
  252. Q42: What if I forget the "[]" when "delete"ing array allocated via "new
  253.    Fred[n]"?
  254. Q43: Is it legal (and moral) for a member function to say "delete this"?
  255. Q44: How do I allocate multidimensional arrays using new?
  256. Q45: Does C++ have arrays whose length can be specified at run-time?
  257. Q46: How can I ensure objects of my class are always created via "new" rather
  258.    than as locals or global/static objects?
  259.  
  260. SECTION 10: Debugging and error handling
  261. Q47: How can I handle a constructor that fails?
  262. Q48: How should I handle resources if my constructors may throw exceptions?
  263.  
  264. SECTION 11: Const correctness
  265. Q49: What is "const correctness"?
  266. Q50: Should I try to get things const correct "sooner" or "later"?
  267. Q51: What is a "const member function"?
  268. Q52: What do I do if I want to update an "invisible" data member inside a
  269.    "const" member function?
  270. Q53: Does "const_cast" mean lost optimization opportunities?
  271.  
  272. SECTION 12: Inheritance
  273. Q54: Is inheritance important to C++?
  274. Q55: When would I use inheritance?
  275. Q56: How do you express inheritance in C++?
  276. Q57: Is it ok to convert a pointer from a derived class to its base class?
  277. Q58: Derived* --> Base* works ok; why doesn't Derived** --> Base** work?
  278. Q59: Does array-of-Derived is-NOT-a-kind-of array-of-Base mean arrays are
  279.    bad?
  280. SUBSECTION 12A: Inheritance -- Virtual functions
  281. Q60: What is a "virtual member function"?
  282. Q61: How can C++ achieve dynamic binding yet also static typing?
  283. Q62: Should a derived class replace ("override") a non-virtual fn from a base
  284.    class?
  285. Q63: What's the meaning of, "Warning: Derived::f(int) hides Base::f(float)"?
  286. SUBSECTION 12B: Inheritance -- Conformance
  287. Q64: Should I hide public member fns inherited from my base class?
  288. Q65: Is a "Circle" a kind-of an "Ellipse"?
  289. Q66: Are there other options to the "Circle is/isnot kind-of Ellipse"
  290.    dilemma?
  291. Q67: But I have a Ph.D. in Mathematics, and I'm SURE a Circle is a kind of an
  292.    Ellipse!  Does this mean Marshall Cline is stupid?  Or that C++ is stupid?  Or
  293.    that OO is stupid?
  294. Q68: But my problem doesn't have anything to do with circles and ellipses, so
  295.    what good is that silly example to me?
  296. SUBSECTION 12C: Inheritance -- Access rules
  297. Q69: Why can't my derived class access "private" things from my base class?
  298. Q70: What's the difference between "public:", "private:", and "protected:"?
  299. Q71: How can I protect subclasses from breaking when I change internal parts?
  300. SUBSECTION 12D: Inheritance -- Constructors and destructors
  301. Q72: When my base class's constructor calls a virtual function, why doesn't my
  302.    derived class's override of that virtual function get invoked?
  303. Q73: Does a derived class destructor need to explicitly call the base
  304.    destructor?
  305. SUBSECTION 12E: Inheritance -- Private and protected inheritance
  306. Q74: How do you express "private inheritance"?
  307. Q75: How are "private inheritance" and "composition" similar?
  308. Q76: Which should I prefer: composition or private inheritance?
  309. Q77: Should I pointer-cast from a "privately" derived class to its base
  310.    class?
  311. Q78: How is protected inheritance related to private inheritance?
  312. Q79: What are the access rules with "private" and "protected" inheritance?
  313.  
  314. SECTION 13: Abstraction
  315. Q80: What's the big deal of separating interface from implementation?
  316. Q81: How do I separate interface from implementation in C++ (like Modula-2)?
  317. Q82: What is an ABC ("abstract base class")?
  318. Q83: What is a "pure virtual" member function?
  319. Q84: How can I provide printing for an entire hierarchy of classes?
  320. Q85: When should my destructor be virtual?
  321. Q86: What is a "virtual constructor"?
  322.  
  323. ========== POSTING #3 ==========
  324.  
  325. SECTION 14: Style guidelines
  326. Q87: What are some good C++ coding standards?
  327. Q88: Are coding standards necessary?  Are they sufficient?
  328. Q89: Should our organization determine coding standards from our C
  329.    experience?
  330. Q90: Should I declare locals in the middle of a fn or at the top?
  331. Q91: What source-file-name convention is best? "foo.C"? "foo.cc"? "foo.cpp"?
  332. Q92: What header-file-name convention is best? "foo.H"? "foo.hh"? "foo.hpp"?
  333. Q93: Are there any lint-like guidelines for C++?
  334.  
  335. SECTION 15: Keys for Smalltalk programmers to learn C++
  336. Q94: Why does C++'s FAQ have a section on Smalltalk? Is this
  337.    Smalltalk-bashing?
  338. Q95: What's the difference between C++ and Smalltalk?
  339. Q96: What is "static typing", and how is it similar/dissimilar to Smalltalk?
  340. Q97: Which is a better fit for C++: "static typing" or "dynamic typing"?
  341. Q98: How can you tell if you have a dynamically typed C++ class library?
  342. Q99: How do you use inheritance in C++, and is that different from Smalltalk?
  343. Q100: What are the practical consequences of diffs in Smalltalk/C++
  344.    inheritance?
  345. Q101: Do you need to learn a "pure" OOPL before you learn C++?
  346. Q102: What is the NIHCL?  Where can I get it?
  347.  
  348. SECTION 16: Reference and value semantics
  349. Q103: What is value and/or reference semantics, and which is best in C++?
  350. Q104: What is "virtual data," and how-can / why-would I use it in C++?
  351. Q105: What's the difference between virtual data and dynamic data?
  352. Q106: Should I normally use pointers to freestore allocated objects for my
  353.    data members, or should I use "composition"?
  354. Q107: What are relative costs of the 3 performance hits associated with
  355.    allocating member objects from the freestore?
  356. Q108: Are "inline virtual" member fns ever actually "inlined"?
  357. Q109: Sounds like I should never use reference semantics, right?
  358. Q110: Does the poor performance of ref semantics mean I should pass-by-value?
  359.  
  360. ========== POSTING #4 ==========
  361.  
  362. SECTION 17: Linkage-to/relationship-with C
  363. Q111: How can I call a C function "f(int,char,float)" from C++ code?
  364. Q112: How can I create a C++ function "f(int,char,float)" that is callable by
  365.    my C code?
  366. Q113: Why's the linker giving errors for C/C++ fns being called from C++/C
  367.    fns?
  368. Q114: How can I pass an object of a C++ class to/from a C function?
  369. Q115: Can my C function access data in an object of a C++ class?
  370. Q116: Why do I feel like I'm "further from the machine" in C++ as opposed to
  371.    C?
  372.  
  373. SECTION 18: Pointers to member functions
  374. Q117: Is the type of "ptr-to-member-fn" different from "ptr-to-fn"?
  375. Q118: How do I pass a ptr to member fn to a signal handler, X event callback,
  376.    etc?
  377. Q119: Why do I keep getting compile errors (type mismatch) when I try to use a
  378.    member function as an interrupt service routine? 
  379. Q120: Why am I having trouble taking the address of a C++ function?
  380. Q121: How do I declare an array of pointers to member functions?
  381.  
  382. SECTION 19: Container classes and templates
  383. Q122: How can I build a <favorite container> of objects of different types?
  384. Q123: How can I insert/access/change elements from a linked
  385.    list/hashtable/etc?
  386. Q124: What's the idea behind "templates"?
  387. Q125: What's the syntax / semantics for a "function template"?
  388. Q126: What's the syntax / semantics for a "class template"?
  389. Q127: What is a "parameterized type"?
  390. Q128: What is "genericity"?
  391.  
  392. SECTION 20: Libraries
  393. Q129: Where can I get a copy of "STL"?
  394. Q130: Where can I ftp the code that accompanies "Numerical Recipes"?
  395. Q131: Why is my executable so large?
  396.  
  397. SECTION 21: Nuances of particular implementations
  398. Q132: GNU C++ (g++) produces big executables for tiny programs; Why?
  399. Q133: Is there a yacc-able C++ grammar?
  400. Q134: What is C++ 1.2?  2.0?  2.1?  3.0?
  401. Q135: If name mangling was standardized, could I link code compiled with
  402.    compilers from different compiler vendors?
  403.  
  404. SECTION 22: Miscellaneous technical and environmental issues
  405. SUBSECTION 22A: Miscellaneous technical issues:
  406. Q136: Why are classes with static data members getting linker errors?
  407. Q137: What's the difference between the keywords struct and class?
  408. Q138: Why can't I overload a function by its return type?
  409. Q139: What is "persistence"?  What is a "persistent object"?
  410. Q140: Why is floating point so inaccurate?  Why doesn't this print 0.43?
  411. SUBSECTION 22B: Miscellaneous environmental issues:
  412. Q141: Is there a TeX or LaTeX macro that fixes the spacing on "C++"?
  413. Q142: Where can I access C++2LaTeX, a LaTeX pretty printer for C++ source?
  414. Q143: Where can I access "tgrind," a pretty printer for C++/C/etc source?
  415. Q144: Is there a C++-mode for GNU emacs?  If so, where can I get it?
  416. Q145: Where can I get OS-specific FAQs answered (e.g.,BC++,DOS,Windows,etc)?
  417. Q146: Why does my DOS C++ program says "Sorry: floating point code not
  418.    linked"?
  419. Q147: Why does my BC++ Windows app crash when I'm not running the BC45 IDE?
  420. ==============================================================================
  421. SUBSECTION 1C: Nomenclature, Acronyms, and Common Abbreviations
  422. ==============================================================================
  423.  
  424. Here are a few of the abbreviations/acronyms/etc used in comp.lang.c++ and in
  425. this on-line document:
  426.  
  427.     Term    Meaning
  428.     ====    ===========
  429.     C++ARM    C++ Annotated Reference Manual (an Addison-Wesley book)
  430.     C++PL2    C++ Programming Language Second Ed. (an Addison-Wesley book)
  431.     fn        function
  432.     fns        functions
  433.     method    an alternate term for "member function"
  434.     OO        object-oriented
  435.     OOP        object-oriented programming
  436.     OOPL    object-oriented programming language
  437.     param    parameter
  438.     ptr        pointer, a C/C++ construct declared by:  int * p;
  439.     ref        reference, a C++ construct declared by:  int & r;
  440.     RTTI    Run-time type identification
  441.  
  442. ==============================================================================
  443. SECTION 2: How should I post something? (READ BEFORE POSTING)
  444. ==============================================================================
  445.  
  446. Q4: Which newsgroup should I post my questions?
  447.  
  448. Comp.lang.c++ is the best place to discuss the C++ language itself (e.g.,
  449. C++ code design, syntax, style).  Other newsgroups exist for discussion of
  450. topics which are specific to a particular system (e.g., MS Windows or UNIX)
  451. or topics which are not directly related to the C++ language (e.g., how to
  452. use your compiler).  Here's a list of some very active newsgroups and
  453. excerpts from their Frequently Asked Questions lists.  These excerpts
  454. should give you an idea of the type of topics frequently discussed there.
  455.  
  456.   comp.os.ms-windows.programmer.tools
  457.      This group is intended for discussions about the selection and use of
  458.      tools for Windows software development.
  459.   comp.os.ms-windows.programmer.misc
  460.      This group is for all other discussions about Windows software
  461.      development.
  462.   [There's one FAQ list for all the comp.os.ms-windows.programmer.* groups]
  463.      FAQ 5.7.1.  Accessing C++ classes in a DLL
  464.      FAQ 6.1.1.  A dialog as an MDI child window [with OWL]
  465.      FAQ 6.2.1.  Disabled menu choices become enabled [with MFC]
  466.      FAQ 8.1.5.  Using STRICT with windows.h
  467.      FAQ 10.  A programmer's bibliography
  468.  
  469.   comp.os.msdos.programmer
  470.      Much of the traffic is about language products (chiefly from Borland
  471.      and Microsoft).
  472.      FAQ 301. How can I read a character without [waiting for] the Enter key?
  473.      FAQ 412. How can I read, create, change, or delete the volume label?
  474.      FAQ 504. How do I configure a COM port and use it to transmit data?
  475.      FAQ 602. How can a C program send control codes to my printer?
  476.      FAQ 606. How can I find the Microsoft mouse position and button status?
  477.      FAQ 707. How can I write a TSR (terminate-stay-resident) utility?
  478.      FAQ B0. How can I contact [Borland, Microsoft]?
  479.      [note: this FAQ is not available at rtfm.mit.edu; it is at Simtel
  480.             (e.g., oak.oakland.edu) in /pub/msdos/info/faqp*.zip and Garbo
  481.             (garbo.uwasa.fi) in /pc/doc-net/faqp*.zip]
  482.   comp.os.msdos.programmer.turbovision [Borland's character-mode framework]
  483.  
  484.   comp.unix.programmer
  485.      FAQ 4.5)  How do I use popen() to open a process for reading AND writing?
  486.      FAQ 4.6)  How do I sleep() in a C program for less than one second?
  487.  
  488.   comp.unix.solaris (covers SunOS 4.x and Solaris)
  489.      FAQ 4)  Signal Primer
  490.      FAQ 5)  Waiting for Children to Exit
  491.  
  492.   gnu.g++.help
  493.      FAQ: Where can I find a demangler?
  494.      FAQ: Getting gcc/g++ binaries for Solaris 2.x
  495.      FAQ: What documentation exists for g++ 2.x?
  496.   gnu.g++.bug [bug reports for g++ -- see the g++ docs]
  497.  
  498.   comp.lang.c
  499.      FAQ 1.10: I'm confused.  NULL is guaranteed to be 0, but the null
  500.                pointer is not?
  501.      FAQ 2.3:  So what is meant by the "equivalence of pointers and
  502.                arrays" in C?
  503.      FAQ 4.2:  [Why doesn't "printf("%d\n," i++ * i++);" work?]
  504.      FAQ 7.1:  How can I write a function that takes a variable number
  505.                of arguments? [stdarg.h or varargs.h]
  506.      FAQ 10.4: How do I declare an array of pointers to functions returning
  507.                pointers to functions returning pointers to characters?
  508.  
  509. Also check out the newsgroups comp.graphics, comp.sources.wanted,
  510. comp.programming, and comp.object (its FAQ is an excellent introduction and
  511. overview of OOP terms and concepts).  Remember that comp.std.c++ is for
  512. discussion DIRECTLY related to the evolving ANSI/ISO C++ Standard (see more
  513. below). 
  514.  
  515. There's rarely a need to crosspost a question to one of the above
  516. newsgroups and comp.lang.c++ (readers in the system-specific newsgroups
  517. aren't programming in machine language, ya know).  It's bad netiquette to
  518. crosspost widely because your problem is "really important."  If you don't
  519. get an answer in the "right" newsgroup and feel you must post here, at
  520. least consider redirecting followups back to the appropriate newsgroup.
  521.  
  522. Before posting a question to any newsgroup you should read it's FAQ list.
  523. An answer to your question is likely to be there, saving you the time of
  524. posting and saving thousands of other people around the world the time of
  525. reading your question.  People answering a FAQ are likely to be annoyed for
  526. having to answer it for the umpteenth time, or they're likely to be giving
  527. you a wrong or incomplete answer since they haven't read the FAQ either.
  528.  
  529. Frequently Asked Questions lists are available 24-hours a day via anonymous
  530. ftp (rtfm.mit.edu in /pub/usenet/comp.what.ever) or e-mail server (send a
  531. message with the line "help" to mail-server@rtfm.mit.edu).  See the article
  532. "Introduction to the *.answers newsgroups" in the newsgroup news.answers or
  533. news.announce.newusers (which contains many other must-read articles) for
  534. more information.
  535.  
  536. ==============================================================================
  537.  
  538. Q5: How do I post a question about code that doesn't work correctly?
  539.  
  540. Here's some guidelines you should follow that will help people reading
  541. comp.lang.c++ help you with an answer to your programming problem.
  542.  
  543. 1. Please read the previous FAQ to make sure that your question is about the
  544.    C++ language and not a question about programming on your system (e.g.,
  545.    graphics, printers, devices, etc.) or using your compilation
  546.    environment (e.g., "the IDE crashes when I...," "how do you turn off
  547.    warnings about...," "how do I tell it to link my libraries").  If you
  548.    want to know why your virtual CmOk() function isn't being called in
  549.    your OWL program, your question is probably more appropriate in the
  550.    Windows programming newsgroup.  If you can write a small stand-alone
  551.    program which exhibits the same undesired compiler error or behavior
  552.    as your OWL program, by all means post here in comp.lang.c++ since C++
  553.    programmers using other systems could be of help.
  554.  
  555. 2. Be descriptive in the subject line.  "C++ problem" leaves a lot to the
  556.    imagination.  "Problem new'ing a multi-dimensional array" is good.
  557.    Refrain from exclamation points, cries for HELPPP, and the once funny
  558.    "SEX SEX SEX."  If you think the problem is specific to your compiler,
  559.    you might want to mention the compiler/version in the subject line.
  560.  
  561. 3. Post code that is complete and compilable.  It's extremely difficult
  562.    to debug or reconstruct a program from a human language description.
  563.    By "complete code" I mean that any types and functions used are
  564.    declared, headers are #include'd, etc.  Please strip the code down to
  565.    the bare essentials.  We don't need a program that does something
  566.    useful at run-time, or even links.  We just need to be able to
  567.    reproduce the undesired compiler error (possibly on a different
  568.    compiler).  By "compilable code" I mean that it doesn't contain a
  569.    bunch of uncommented ellipses or line numbers at the beginning of each
  570.    line:
  571.  
  572.     14:    #include <iostream.h>
  573.     15:    class Foo { ... };  // this is annoying
  574.  
  575.    Try to organize the code into one linear program instead of making us cut
  576.    out and create header files.  Be very careful if you are typing the code
  577.    into your article -- it's often difficult to tell whether something is a
  578.    typo or the real cause of the problem.  Try using your editor's
  579.    cut&paste or "insert file" feature instead.
  580.  
  581. 4. Mention what compiler, compiler version, and system you're using.  I
  582.    know, I just said that system-specific questions should go to a
  583.    system-specific newsgroup, but compiler information is often very
  584.    useful in diagnosing the problem: ("yeah, I remember Acme 1.2 having
  585.    lots of problems in this area").  It also warns other users of that
  586.    compiler about possible bugs.
  587.  
  588. 5. Show us the exact compiler and linker options and libraries you used
  589.    when building your program.
  590.  
  591. 6. List the exact error message and where the error was given.  "Virtual
  592.    functions don't work" doesn't tell us whether its a compile-, link-, or
  593.    run-time problem.  If the problem is at run-time, give a good
  594.    description of the behavior and any relevant information about your
  595.    system setup.
  596.  
  597. 7. Include a working e-mail address in your signature.  If the address in
  598.    given your article's "From:" line is not correct, please notify your
  599.    system administrator.  Until it is fixed, add a "Reply-To:" line to
  600.    your headers that uses your correct e-mail address.
  601.  
  602. 8. Please read the rest of this FAQ -- chances are your problem, or a
  603.    closely related problem, is discussed here.  Thank you and I hope these
  604.    suggestions help you find a solution to your problem.
  605.  
  606. ==============================================================================
  607. SECTION 3: Environmental/managerial issues
  608. ==============================================================================
  609.  
  610. Q6: What is OOP?  What is C++?
  611.  
  612. OO programming techniques are the best way we know of to develop large, complex
  613. software applications and systems.
  614.  
  615. C++ is an OO programming language.  C++ can be used both as an OOPL and simply
  616. "as a better C."  However if you use it "as a better C," don't expect to get
  617. the benefits of object-oriented programming.
  618.  
  619. OO hype: the software industry is "failing" to meet demands for large, complex
  620. software systems.  But this "failure" is actually due to our SUCCESSES: our
  621. successes have propelled users to ask for more.  Unfortunately we created a
  622. market hunger that the "structured" analysis, design and programming techniques
  623. couldn't satisfy.  This required us to create a better paradigm.
  624.  
  625. ==============================================================================
  626.  
  627. Q7: Is C++ better than Ada? (or Pascal, C, FORTRAN, Visual Basic, or any other
  628.    language?)
  629.  
  630. This question generates much MUCH more heat than light.  Please read this
  631. before posting some variant of this question.
  632.  
  633. In 99% of the cases, programming language selection is dominated by business
  634. considerations, NOT by technical considerations.  Things that REALLY end up
  635. mattering are things like availability of a programming environment for the
  636. development machine, availability of runtime environment(s) for the deployment
  637. machine(s), licensing/legal issues of the runtime and/or development
  638. environments, availability of trained developers, availability of consulting
  639. services, and corporate culture/politics.  These business considerations
  640. generally play a much greater role than compile time performance, runtime
  641. performance, static vs. dynamic typing, static vs. dynamic binding, etc.
  642.  
  643. Therefore anyone who argues in favor of one language over another in a purely
  644. technical manner (i.e., who ignores the dominant business issues) exposes
  645. themselves as a techie weenie, and deserves not to be heard.
  646.  
  647. ==============================================================================
  648.  
  649. Q8: What are some advantages of C++?
  650.  
  651. GROWTH OF C++: C++ is by far the most popular OOPL.  The number of C++ users is
  652. doubling every 7.5 to 9 months.  Knowing C++ is a good resume-stuffer (but use
  653. it as an OOPL rather than just as a better C).
  654.  
  655. ENCAPSULATION: Hiding our data structures allows us to change one chunk of a
  656. system without breaking other chunks.  We provide our software chunks (we call
  657. them "classes") with safe interfaces.  Users of a chunk use its interface only.
  658. The relatively volatile "implementation" of this interface is "encapsulated"
  659. ("put into a capsule") to prevent users from becoming reliant on its temporary
  660. decisions.  In simple C, this was done by making a module's data "static", thus
  661. preventing another module from accessing our module's bits.
  662.  
  663. MULTIPLE INSTANCES: The typical C solution to encapsulation (see above) doesn't
  664. support multiple instances of the data (it's hard to make multiple instances of
  665. a module's "static" data).  If we needed multiple instances in C, we used a
  666. "struct" (but this doesn't support "encapsulation").  In C++, we can have both
  667. multiple instances and encapsulation via a "class": the "public" part of a
  668. class contains the class's interface (normally these are a special kind of
  669. function called a "member function"), and the "private" part of a class
  670. contains the class's implementation (typically these are where the bits live).
  671.  
  672. INLINE FUNCTION CALLS: In straight C, you can achieve "encapsulated structs" by
  673. putting a "void*" in a struct (the access functions use pointer casts).  This
  674. forfeits type safety, and also imposes a function call to access even trivial
  675. fields of the struct (if you allowed direct access to the struct's fields, the
  676. underlying data structure would be difficult to change since too many chunks
  677. would RELY on it being the "old" way).  Function call overhead is small, but
  678. can add up.  C++ classes allow function calls to be expanded "inline," so you
  679. have: the 1) safety of encapsulation, 2) convenience of multiple instances, 3)
  680. speed of direct access.  Furthermore the parameter types of these inline
  681. functions are checked by the compiler, an improvement over C's #define macros.
  682.  
  683. OVERLOADING OPERATORS: C++ lets you overload the standard operators on a class,
  684. which lets users exploit their intuition (e.g., "myString + yourString" might
  685. do string concatenation, "myDate++" might increment the date, "z1 * z2" might
  686. multiply complex numbers z1 and z2, "a[i]" might access the "i"th element of
  687. the "linked list" called "a", etc.  You can even have "smart pointers" that
  688. could "point" to a disk record or wherever ("x = *p" could "dereference" such a
  689. pointer, which could seek to the location on disk where p "points" and return
  690. its value").  This allows users to program in the language of the problem
  691. domain rather than in the language of the machine.
  692.  
  693. INHERITANCE: We still have just scratched the surface.  In fact, we haven't
  694. even gotten to the "object-oriented" part yet!  Suppose you have a Stack data
  695. type with operations push, pop, etc.  Suppose you want an InvertableStack,
  696. which is "just like" Stack except it also has an "invert" operation.  In "C"
  697. style, you'd have to either (1) modify the existing Stack module (trouble if
  698. "Stack" is being used by others), or (2) copy Stack into another file and text
  699. edit that file (results in lots of code duplication, another chance to break
  700. something tricky in the Stack part of InvertableStack, and especially twice as
  701. much code to maintain).  C++ provides a much cleaner solution: inheritance.
  702. You say "InvertableStack inherits everything from Stack, and InvertableStack
  703. adds the invert operation."  Done.  Stack itself remains "closed" (untouched,
  704. unmodified), and InvertableStack doesn't duplicate the code for push/pop/etc.
  705.  
  706. POLYMORPHISM AND DYNAMIC BINDING: The real power of OOP isn't just inheritance,
  707. but is the ability to pass an InvertableStack around as if it actually were a
  708. Stack.  This is "safe" since (in C++ at least) the is-a relation follows public
  709. inheritance (i.e., a InvertableStack is-a Stack that can also invert itself).
  710. Polymorphism and dynamic binding are easiest to understand from an example, so
  711. here's a "classic": a graphical draw package might deal with Circles, Squares,
  712. Rectangles, general Polygons, and Lines.  All of these are Shapes.  Most of the
  713. draw package's functions need a "Shape" parameter (as opposed to some
  714. particular kind of shape like Square).  E.g., if a Shape is picked by a mouse,
  715. the Shape might get dragged across the screen and placed into a new location.
  716. Polymorphism and dynamic binding allow the code to work correctly even if the
  717. compiler knows only that the parameter is a "Shape" without knowing the exact
  718. kind of Shape it is.  Furthermore suppose the "pick_and_drag(Shape*) function
  719. just mentioned was compiled on Tuesday, and on Wednesday you decide to add the
  720. Hexagon shape.  Strange as it sounds, pick_and_drag() will still work with
  721. Hexagons, even though the Hexagon didn't even exist when pick_and_drag() was
  722. compiled!!  (it's not really "amazing" once you understand how the C++ compiler
  723. does it -- but it's still very convenient!)
  724.  
  725. ==============================================================================
  726.  
  727. Q9: Who uses C++?
  728.  
  729. Lots and lots of companies and government sites.  Lots.
  730.  
  731. Statistically, 5 people became new C++ programmers while you read the words of
  732. the previous FAQ.
  733.  
  734. ==============================================================================
  735.  
  736. Q10: Are there any C++ standardization efforts underway?
  737.  
  738. Yes; ANSI (American) and ISO (International) groups are working closely with
  739. each other.  The ANSI-C++ committee is called "X3J16".  The ISO C++ standards
  740. group is called "WG21".  The major players in the ANSI/ISO C++ standards
  741. process includes just about everyone:
  742.  
  743. AT&T, IBM, DEC, HP, Sun, MS, Borland, Zortech, Apple, OSF, etc ad nauseum.
  744. About 70 people attend each meeting.  People come from USA, UK, Japan, Germany,
  745. Sweden, Denmark, France, ... (all have "local" committees sending official
  746. representatives and conducting "local" meetings).
  747.  
  748. ==============================================================================
  749.  
  750. Q11: Where can I get a copy of the latest ANSI-C++ draft standard?
  751.  
  752. The ISO Committee Draft for C++ and the ANSI C++ Draft (the document that is
  753. going out for public review) is available from:
  754.     http://www.cygnus.com/~mrs/wp-draft
  755.  
  756. You can also get Postscript and Adobe Acrobat versions from:
  757.     ftp://research.att.com/dist/c++std/WP
  758.     ftp://ftp.maths.warwick.ac.uk:/pub/c++/std/WP
  759.     ftp://ftpt.su.edu.au:/pub/C++/CommitteeDraft
  760.  
  761. You can get HTML and ASCII versions:
  762.     ftp://ftp.cygnus.com/pub/g++
  763.  
  764. You can also get a paper copy from:
  765.     X3 Secretariat
  766.     1250 Eye Street NW
  767.     Suite 200
  768.     Washington, DC  20005
  769.     202-626-5738
  770.  
  771. You can also order via email:
  772.     lbarra@itic.nw.dc.us (Lynn Barra)
  773.  
  774. Ask for the latest version of "Draft Proposed American National Standard for
  775. Information Systems -- Programming Language C++" which is document number
  776. CD14882.  It is typically shipped 2-day FedEx (within the continental US), so
  777. people usually get it quickly.
  778.  
  779. ==============================================================================
  780.  
  781. Q12: Is C++ backward compatible with ANSI-C?
  782.  
  783. Almost.
  784.  
  785. C++ is as close as possible to compatible with C, but no closer.  In practice,
  786. the major difference is that C++ requires prototypes, and that "f()" declares a
  787. function that takes no parameters (in C, "f()" is the same as "f(...)").  There
  788. are some very subtle differences as well, like sizeof('x') is equal to
  789. sizeof(char) in C++ but is equal to sizeof(int) in C.  Also, C++ puts structure
  790. "tags" in the same namespace as other names, whereas C requires an explicit
  791. "struct" (the "typedef struct Fred Fred" technique still works, but is
  792. redundant in C++).
  793.  
  794. ==============================================================================
  795.  
  796. Q13: How long does it take to learn C++?
  797.  
  798. Companies like Paradigm Shift, Inc. successfully teach standard industry "short
  799. courses", where we compress a university semester course into one 40hr work
  800. week.  However true mastery takes experience; there's no substitute for time.
  801. Hands-on projects are essential, since they allow concepts to "gel."
  802.  
  803. It takes 6-12 months to become proficient in C++/OOP.  Less if the developers
  804. have easy access to a "local" body of experts, more if there isn't a "good"
  805. general purpose C++ class library available.  To become one of these experts
  806. who can mentor others takes around 3 years.
  807.  
  808. Some people never make it.  You don't have a chance unless you are teachable
  809. and have personal drive.  As a bare minimum on "teachability," you have to be
  810. able to admit when you've are wrong.  As a bare minimum on "drive," you must
  811. be willing to put in some extra hours (changing the way you think [a paradigm
  812. shift] is a LOT more painful than learning a few new facts).
  813.  
  814. ==============================================================================
  815. SECTION 4: Basics of the paradigm
  816. ==============================================================================
  817.  
  818. Q14: What is a class?
  819.  
  820. The fundamental building block of OO software.
  821.  
  822. A class defines a data type, much like a struct would be in C.  In a computer
  823. science sense, a type consists of both a set of states AND a set of operations
  824. which transition between those states.  Thus "int" is a "type" because it has
  825. both a set of states AND it has operations like "add two ints" or "int*int,"
  826. etc.  In exactly the same way, a "class" provides a set of (usually public)
  827. operations, and a set of (usually non-public) data bits representing the
  828. abstract values that instances of the type can have.  From a C language
  829. perspective, a class is a struct whose members default to "private".
  830.  
  831. Think of "int" as a class that has methods called "operator++", etc.
  832.  
  833. ==============================================================================
  834.  
  835. Q15: What is an object?
  836.  
  837. A region of storage with associated semantics.
  838.  
  839. After the declaration "int i;" we say that "i is an object of type int."  In
  840. C++/OOP, "object" usually means "an instance of a class."  Thus a class defines
  841. the behavior of possibly many objects (instances).
  842.  
  843. ==============================================================================
  844.  
  845. Q16: What is a reference?
  846.  
  847. An alias (an alternate name) for an object.
  848.  
  849. References are frequently used for pass-by-reference:
  850.  
  851.     void swap(int& i, int& j)
  852.     {
  853.       int tmp = i;
  854.       i = j;
  855.       j = tmp;
  856.     }
  857.  
  858.     main()
  859.     {
  860.       int x, y;
  861.       //...
  862.       swap(x,y);
  863.     }
  864.  
  865. Here "i" and "j" are aliases for main's "x" and "y" respectively.  In other
  866. words, "i" IS "x" -- not a pointer to "x", nor a copy of "x", but "x" itself.
  867. Anything you do to "i" gets done to "x", and vise versa.
  868.  
  869. Underneath it all, references are typically implemented by pointers.  The
  870. effect is as if you used the C style pass-by-pointer, but the "&" is moved from
  871. the caller into the callee, and you eliminate all the "*"s.
  872.  
  873. ==============================================================================
  874.  
  875. Q17: What happens if you assign to a reference?
  876.  
  877. You change the referrent (the object to which the reference refers).
  878.  
  879. Remember: the reference IS the referrent, so changing the reference changes the
  880. referrent (a reference is an "Lvalue" [something that can appear on the
  881. "L"eft-hand-side of an assignment statement] for the referrent).
  882.  
  883. This insight can be pushed a bit farther by allowing references to be RETURNED.
  884. This allows function calls on the left hand side of an assignment statement,
  885. which is useful with operator overloading.
  886.  
  887. ==============================================================================
  888.  
  889. Q18: How can you reseat a reference to make it refer to a different object?
  890.  
  891. No way.
  892.  
  893. Unlike a pointer, once a reference is bound to an object, it can NOT be
  894. "reseated" to another object.  The reference itself isn't an object (it has no
  895. address; taking the address of a reference gives you the address of the
  896. referrent; remember: the reference IS its referrent).
  897.  
  898. You can't separate the reference from the referent.
  899.  
  900. ==============================================================================
  901.  
  902. Q19: When should I use references, and when should I use pointers?
  903.  
  904. Use references when you can, and pointers when you have to.
  905.  
  906. References are usually preferred over ptrs whenever you don't need "reseating"
  907. (see previous FAQ).  This usually means that references are most useful in a
  908. class's public interface.  References typically appear on the skin of an
  909. object, and pointers on the inside.
  910.  
  911. The exception to the above is where a function's parameter or return value
  912. needs a "sentinel" reference.  This is usually best done by returning/taking a
  913. pointer, and giving the NULL pointer this special significance (references
  914. should always alias objects, not a dereferenced NULL ptr).
  915.  
  916. NOTE: Old line C programmers sometimes don't like references since they provide
  917. reference semantics that isn't explicit in the caller's code.  After some C++
  918. experience, however, one quickly realizes this is a form of information hiding,
  919. which is an asset rather than a liability.  E.g., programmers should write code
  920. in the language of the problem rather than the language of the machine.
  921.  
  922. ==============================================================================
  923.  
  924. Q20: What's the deal with inline functions?
  925.  
  926. An inline function is a function whose code gets inserted into the caller's
  927. code stream.  Like a macro, inline functions improve performance by avoiding
  928. the overhead of the call itself and (especially!) by the compiler being able to
  929. optimize THROUGH the call ("procedural integration").  Unlike macros, inline
  930. functions avoid infamous macro errors by evaluating all arguments exactly once
  931. (the "call" is semantically like a regular function call, only faster).  Also
  932. unlike macros, argument types are checked, and necessary conversions are
  933. performed correctly (macros are bad for your health; don't use them unless you
  934. absolutely have to).
  935.  
  936. Beware that overuse of inline functions can cause code bloat, which can in
  937. turn have a negative performance impact in paging environments.
  938.  
  939. They are declared by using the "inline" keyword when the function is defined:
  940.  
  941.     inline void f(int i, char c) { /*...*/ }
  942.  
  943. or by including the function definition itself within a class:
  944.  
  945.     class Fred {
  946.     public:
  947.       void f(int i, char c) { /*...*/ }
  948.     };
  949.  
  950. or by defining the member function as "inline" outside the class:
  951.  
  952.     class Fred {
  953.     public:
  954.       void f(int i, char c);
  955.     };
  956.  
  957.     inline void Fred::f(int i, char c) { /*...*/ }
  958.  
  959. ==============================================================================
  960. SECTION 5: Constructors and destructors
  961. ==============================================================================
  962.  
  963. Q21: What's the deal with constructors?
  964.  
  965. Constructors build objects from dust.
  966.  
  967. Constructors are like "init functions"; they turn a pile of arbitrary bits into
  968. a living object.  Minimally they initialize internally used fields.  They may
  969. also allocate resources (memory, files, semaphores, sockets, etc).
  970.  
  971. "ctor" is a typical abbreviation for constructor.
  972.  
  973. ==============================================================================
  974.  
  975. Q22: How can I make a constructor call another constructor as a primitive?
  976.  
  977. No way.
  978.  
  979. Dragons be here: if you call another constructor, the compiler initializes a
  980. temporary local object; it does NOT initialize "this" object.  You can combine
  981. both constructors by using a default parameter, or you can share their common
  982. code in a private "init()" member function.
  983.  
  984. ==============================================================================
  985.  
  986. Q23: What's the deal with destructors?
  987.  
  988. A destructor gives an object its last rites.
  989.  
  990. Destructors are used to release any resources allocated by the object.  E.g., a
  991. Lock class might lock a semaphore, and the destructor will release that
  992. semaphore.  The most common example is when the constructor uses "new", and the
  993. destructor uses "delete".
  994.  
  995. Destructors are a "prepare to die" method.  They are often abbreviated "dtor".
  996.  
  997. ==============================================================================
  998. SECTION 6: Operator overloading
  999. ==============================================================================
  1000.  
  1001. Q24: What's the deal with operator overloading?
  1002.  
  1003. It allows users of your classes to use intuitive syntax.
  1004.  
  1005. Operator overloading allows C/C++ operators to have user-defined meanings on
  1006. user-defined types (classes).  They're syntactic sugar for function calls:
  1007.  
  1008.     class Fred {
  1009.     public:
  1010.       //...
  1011.     };
  1012.  
  1013.     #if 0
  1014.       Fred add(Fred, Fred);        //without operator overloading
  1015.       Fred mul(Fred, Fred);
  1016.     #else
  1017.       Fred operator+(Fred, Fred);    //with operator overloading
  1018.       Fred operator*(Fred, Fred);
  1019.     #endif
  1020.  
  1021.     Fred f(Fred a, Fred b, Fred c)
  1022.     {
  1023.       #if 0
  1024.         return add(add(mul(a,b), mul(b,c)), mul(c,a));  //without...
  1025.       #else
  1026.         return a*b + b*c + c*a;                         //with...
  1027.       #endif
  1028.     }
  1029.  
  1030. ==============================================================================
  1031.  
  1032. Q25: What operators can/cannot be overloaded?
  1033.  
  1034. Most can be overloaded. The only C operators that can't be are "." and "?:"
  1035. (and "sizeof," which is technically an operator).  C++ adds a few of its own
  1036. operators, most of which can be overloaded except "::" and ".*".
  1037.  
  1038. Here's an example of the subscript operator (it returns a reference).  First
  1039. withOUT operator overloading:
  1040.  
  1041.     class Array {
  1042.     public:
  1043.       #if 0
  1044.         int& elem(unsigned i) { if (i>99) error(); return data[i]; }
  1045.       #else
  1046.         int& operator[] (unsigned i) { if (i>99) error(); return data[i]; }
  1047.       #endif
  1048.     private:
  1049.       int data[100];
  1050.     };
  1051.  
  1052.     main()
  1053.     {
  1054.       Array a;
  1055.  
  1056.       #if 0
  1057.         a.elem(10) = 42;
  1058.         a.elem(12) += a.elem(13);
  1059.       #else
  1060.         a[10] = 42;
  1061.         a[12] += a[13];
  1062.       #endif
  1063.     }
  1064.  
  1065. ==============================================================================
  1066.  
  1067. Q26: Can I create a "**" operator for "to-the-power-of" operations?
  1068.  
  1069. Nope.
  1070.  
  1071. The names of, precedence of, associativity of, and arity of operators is fixed
  1072. by the language.  There is no "**" operator in C++, so you cannot create one
  1073. for a class type.
  1074.  
  1075. If you're in doubt, consider that "x ** y" is the same as "x * (*y)" (in other
  1076. words, the compiler assumes "y" is a pointer).  Besides, operator overloading
  1077. is just syntactic sugar for function calls.  Although this particular syntactic
  1078. sugar can be very sweet, it doesn't add anything fundamental.  I suggest you
  1079. overload "pow(base,exponent)" (a double precision version is in <math.h>).
  1080.  
  1081. BTW: operator^ can work, except it has the wrong precedence and associativity.
  1082.  
  1083. ==============================================================================
  1084. SECTION 7: Friends
  1085. ==============================================================================
  1086.  
  1087. Q27: What is a "friend"?
  1088.  
  1089. Something to allow your class to grant access to another class or function.
  1090.  
  1091. Friends can be either functions or other classes.  A class grants access
  1092. privileges to its friends.  Normally a developer has political and technical
  1093. control over both the friends and methods of a class (else you need permission
  1094. from the owner of the other pieces when you want to update your class).
  1095.  
  1096. ==============================================================================
  1097.  
  1098. Q28: Do "friends" violate encapsulation?
  1099.  
  1100. If they're used properly, they actually ENHANCE encapsulation.
  1101.  
  1102. You often need to split a class in half when the two halves will have different
  1103. numbers of instances or different lifetimes.  In these cases, the two halves
  1104. usually need direct access to each other (the two halves USED to be in the same
  1105. class, so you haven't INCREASED the number of methods that have direct access
  1106. to a data structure; you've simply MOVED some of those methods).  The safest
  1107. way to implement this is to make the two halves friends of each other.
  1108.  
  1109. If you use friends like just described, you'll keep private things private.  In
  1110. a naive effort to avoid using friendship in situations like the above, many
  1111. people actually destroy encapsulation by either using public data (grotesque!),
  1112. or by making the data accessible between the halves via public get/set methods.
  1113. Having a public get and set method for a private datum is ok only when the
  1114. private datum "makes sense" from outside the class (from a user's perspective).
  1115. In many cases, these get/set methods are almost as bad as public data: they
  1116. hide (only) the NAMES of the private data members, but they don't hide the
  1117. existence of the private data members.
  1118.  
  1119. Similarly, if you use friend functions as a syntactic variant of a class's
  1120. public access functions, they don't violate encapsulation any more than a
  1121. member function violates encapsulation.  In other words, a class's friends and
  1122. members ARE the encapsulation barrier, as defined by the class itself.
  1123.  
  1124. ==============================================================================
  1125.  
  1126. Q29: What are some advantages/disadvantages of using friend functions?
  1127.  
  1128. They provide a degree of freedom in the interface design options.
  1129.  
  1130. Member fns and friend fns are equally privileged (100% vested).  The major
  1131. difference is that a friend function is called like "f(x)", while a member is
  1132. called like "x.f()".  Thus friend fns allow the class's designer to select
  1133. the syntax that is deemed most readable, which lowers maintenance costs.
  1134.  
  1135. The major disadvantage of friend functions is that they require an extra line
  1136. of code when you want dynamic binding.  To get the effect of a virtual friend,
  1137. the friend function should call a hidden (usually "protected:") virtual member
  1138. fn; e.g., "void f(Base& b) { b.do_f(); }".  Derived classes override the hidden
  1139. virtual member function ("void Derived::do_f()"), NOT the friend function.
  1140.  
  1141. ==============================================================================
  1142.  
  1143. Q30: What does it mean that "friendship is neither inherited nor transitive"?
  1144.  
  1145. The privileges of friendship aren't inherited: derived classes of a friend
  1146. aren't necessarily friends (I may declare you as my friend, but that doesn't
  1147. mean I necessarily trust your kids).  If class "Base" declares "f()" to be a
  1148. friend, "f()" doesn't have any automatic special access rights to the extra
  1149. stuff declared in derived class, "Derived."
  1150.  
  1151. The privileges of friendship aren't transitive: friends of a friend class
  1152. aren't necessarily friends of the original class (a friend of a friend isn't
  1153. necessarily a friend).  E.g., if class "Fred" declares class "Wilma" as a
  1154. friend, and class "Wilma" declares "f()" as a friend, "f()" doesn't necessarily
  1155. have any special access rights to "Fred".
  1156.  
  1157. ==============================================================================
  1158.  
  1159. Q31: Should my class declare a member function or a friend function?
  1160.  
  1161. Use a member when you can, and a friend when you have to.
  1162.  
  1163. Sometimes friends are syntactically better (e.g., in class "Fred", friend fns
  1164. allow the "Fred" param to be second, while members require it to be first).
  1165. Another good use of friend functions are the binary infix arithmetic operators
  1166. (e.g., "aComplex + aComplex" probably should be defined as a friend rather than
  1167. a member, since you want to allow "aFloat + aComplex" as well; recall members
  1168. don't allow promotion of the left hand arg, since that would change the class
  1169. of the object that is the recipient of the member function invocation).
  1170.  
  1171. In other cases, choose a member function over a friend function.
  1172.  
  1173. ==============================================================================
  1174. SECTION 8: Input/output via <iostream.h> and <stdio.h>
  1175. ==============================================================================
  1176.  
  1177. Q32: How can I provide printing for a "class Fred"?
  1178.  
  1179. Provide a friend operator<<:
  1180.  
  1181.     class Fred {
  1182.     public:
  1183.       friend ostream& operator<< (ostream& o, const Fred& fred)
  1184.         { return o << fred.i; }
  1185.       //...
  1186.     private:
  1187.       int i;    //just for illustration
  1188.     };
  1189.  
  1190. We use a friend rather than a member since the "Fred" parameter is second
  1191. rather than first.  Input is similar, but the signature is:
  1192.  
  1193.     istream& operator>> (istream& i, Fred& fred);
  1194.                                   // ^^^^^------- not "const Fred& fred"!
  1195.  
  1196. ==============================================================================
  1197.  
  1198. Q33: Why should I use <iostream.h> instead of the traditional <stdio.h>?
  1199.  
  1200. Increase type safety, reduce errors, improve performance, allow extensibility,
  1201. and provide subclassability.
  1202.  
  1203. Printf is arguably not broken, and scanf is perhaps livable despite being error
  1204. prone, however both are limited with respect to what C++ I/O can do.  C++ I/O
  1205. (using "<<" and ">>") is, relative to C (using "printf()" and "scanf()"):
  1206.  
  1207.  * Type safe -- type of object being I/O'd is known statically by the compiler,
  1208.    rather than via dynamically tested via "%" fields.
  1209.  
  1210.  * Less error prone -- redundant info increases the chance of errors.  C++ I/O
  1211.    has no redundant "%" tokens to get right.
  1212.  
  1213.  * Extensible -- the C++ I/O mechanism allows new user-defined types to be
  1214.    added without breaking existing code (imagine the chaos if everyone was
  1215.    simultaneously adding new incompatible "%" fields to printf and scanf?!).
  1216.  
  1217.  * Subclassable -- ostream and istream (the C++ replacements for FILE*) are
  1218.    real classes, and hence subclassable.  This means you can have other user
  1219.    defined things that look and act like streams, yet that do whatever strange
  1220.    and wonderful things you want.  You automatically get to use the zillions of
  1221.    lines of I/O code written by users you don't even know, and they don't need
  1222.    to know about your "extended stream" class.
  1223.  
  1224. ==============================================================================
  1225.  
  1226. Q34: Why does my input seem to process past the end of file?
  1227. Because the eof state is not set until after a read is attempted past the
  1228. end of file.  That is, reading the last byte from a file does not set the
  1229. eof state.
  1230.  
  1231. If your code looks like this:
  1232.  
  1233.     int i = 0;
  1234.     while (! cin.eof())  {
  1235.       cin >> x;
  1236.       ++i;
  1237.       // work with x
  1238.     }
  1239.  
  1240. Then you have an off by one error with the count i.  
  1241. What you really need is:
  1242.  
  1243.     int i;
  1244.     while (cin >> x)  {
  1245.       ++i;
  1246.       // work with x
  1247.     }
  1248.  
  1249. ==============================================================================
  1250.  
  1251. Q35: Why is my program ignoring my input request after the first iteration?
  1252. Because the numerical extractor leaves non digits behind in the input buffer.
  1253.  
  1254. If your code looks like this:
  1255.  
  1256.     char name[1000];
  1257.     int age;
  1258.  
  1259.     for (;;) {
  1260.       cout << "Name: ";
  1261.       cin >> name;
  1262.       cout << "Age: ";
  1263.       cin >> age;
  1264.     }
  1265.  
  1266. What you really want is:
  1267.  
  1268.     for (;;) {
  1269.       cout << "Name: ";
  1270.       cin >> name;
  1271.       cout << "Age: ";
  1272.       cin >> age;
  1273.       cin.ignore(INT_MAX, '\n');
  1274.     }
  1275.  
  1276. ==============================================================================
  1277.  
  1278. Q36: How can I "reopen" cin and cout in binary mode under DOS and/or OS/2?
  1279.  
  1280. Here's the typical scenario that leads to this question: Someone wants to do
  1281. binary I/O using cin and cout, but their operating system (such as DOS or
  1282. OS/2) insists on doing translations on carriagereturn-linefeed pairs.
  1283.  
  1284. Here's the answer: The predefined streams cin, cout, cerr are assumed to be
  1285. text streams, and there is no standard way to cause them to be opened in
  1286. binary mode.  Closing the streams and attempting to reopen them in binary mode
  1287. might have unexpected or undesirable results.
  1288.  
  1289. On systems where it makes a difference, the implementation might provide a way
  1290. to make them binary streams, but you would have to check the manuals to find
  1291. out.
  1292.  
  1293. --
  1294. Paradigm Shift, Inc. / P.O. Box 5108 / Potsdam, NY  13676
  1295. Technology consulting services
  1296. cline@parashift.com / Voice: 315-353-6100 / FAX: 315-353-6110
  1297.